import React, { useState } from 'react';
import { Upload, Button, Slider, Card, Row, Col, Spin, message } from 'antd';
import { InboxOutlined, DownloadOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import Link from 'next/link';
import Layout from '../../components/layout/Layout';
import styles from '../../styles/ToolDetail.module.css';

const { Dragger } = Upload;

const ImageCompressPage = () => {
  const [uploading, setUploading] = useState(false);
  const [compressing, setCompressing] = useState(false);
  const [originalImage, setOriginalImage] = useState(null);
  const [compressedImage, setCompressedImage] = useState(null);
  const [quality, setQuality] = useState(80);
  const [originalSize, setOriginalSize] = useState(0);
  const [compressedSize, setCompressedSize] = useState(0);

  // 上传前检查文件
  const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件!');
      return false;
    }
    
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isLt5M) {
      message.error('图片必须小于5MB!');
      return false;
    }
    
    // 显示原始图片预览
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      setOriginalImage(reader.result);
      setOriginalSize(file.size);
    };
    
    return false; // 阻止自动上传
  };

  // 处理压缩
  const handleCompress = () => {
    if (!originalImage) {
      message.error('请先上传图片');
      return;
    }
    
    setCompressing(true);
    
    // 模拟压缩过程
    // 实际应用中，这里应该调用compressorjs或后端API进行实际压缩
    setTimeout(() => {
      setCompressedImage(originalImage);
      
      // 模拟压缩后的大小 (实际应用中会返回真实压缩后大小)
      const simulatedSize = Math.round(originalSize * (quality / 100));
      setCompressedSize(simulatedSize);
      
      setCompressing(false);
      message.success('图片压缩成功!');
    }, 2000);
  };

  // 格式化文件大小
  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 B';
    
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 下载压缩后的图片
  const handleDownload = () => {
    if (!compressedImage) return;
    
    const link = document.createElement('a');
    link.href = compressedImage;
    link.download = 'compressed-image.jpg';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <Layout title="图片压缩 - 在线工具平台" description="在线压缩图片，减小文件体积">
      <div className={styles.toolHeader}>
        <div className={styles.container}>
          <Link href="/image-tools" className={styles.backLink} legacyBehavior>
            <a className={styles.backLink}>
              <ArrowLeftOutlined /> 返回图片工具
            </a>
          </Link>
          <h1 className={styles.toolTitle}>图片压缩</h1>
          <p className={styles.toolDescription}>
            在保持图片质量的同时减小文件体积，适用于网站图片优化、邮件附件等场景
          </p>
        </div>
      </div>

      <div className={styles.toolContent}>
        <div className={styles.container}>
          <Card className={styles.toolCard}>
            <div className={styles.uploadSection}>
              {!originalImage && (
                <Dragger
                  name="file"
                  multiple={false}
                  beforeUpload={beforeUpload}
                  showUploadList={false}
                  disabled={uploading}
                >
                  <p className="ant-upload-drag-icon">
                    <InboxOutlined />
                  </p>
                  <p className="ant-upload-text">点击或拖拽图片到此区域上传</p>
                  <p className="ant-upload-hint">
                    支持PNG、JPG、JPEG、WEBP格式，单个文件不超过5MB
                  </p>
                </Dragger>
              )}

              {originalImage && !compressedImage && (
                <div className={styles.compressionSettings}>
                  <h3>压缩设置</h3>
                  <div className={styles.qualitySlider}>
                    <span>压缩质量: {quality}%</span>
                    <Slider
                      min={10}
                      max={100}
                      value={quality}
                      onChange={setQuality}
                    />
                    <p className={styles.qualityHint}>
                      较高的质量保留更多细节但文件较大，较低的质量文件更小但可能影响画质
                    </p>
                  </div>
                  
                  <div className={styles.imagePreview}>
                    <img src={originalImage} alt="预览" />
                    <div className={styles.imageInfo}>
                      <span>原始大小: {formatFileSize(originalSize)}</span>
                    </div>
                  </div>
                  
                  <Button
                    type="primary"
                    size="large"
                    onClick={handleCompress}
                    loading={compressing}
                    block
                  >
                    开始压缩
                  </Button>
                </div>
              )}

              {compressedImage && (
                <div className={styles.resultSection}>
                  <h3>压缩结果</h3>
                  
                  <Row gutter={24} className={styles.compareRow}>
                    <Col xs={24} md={12}>
                      <div className={styles.imageCompare}>
                        <h4>原始图片</h4>
                        <div className={styles.imagePreview}>
                          <img src={originalImage} alt="原始图片" />
                          <div className={styles.imageInfo}>
                            <span>大小: {formatFileSize(originalSize)}</span>
                          </div>
                        </div>
                      </div>
                    </Col>
                    
                    <Col xs={24} md={12}>
                      <div className={styles.imageCompare}>
                        <h4>压缩后</h4>
                        <div className={styles.imagePreview}>
                          <img src={compressedImage} alt="压缩后图片" />
                          <div className={styles.imageInfo}>
                            <span>大小: {formatFileSize(compressedSize)}</span>
                            <span className={styles.savedSize}>
                              节省 {Math.round((originalSize - compressedSize) / originalSize * 100)}%
                            </span>
                          </div>
                        </div>
                      </div>
                    </Col>
                  </Row>
                  
                  <div className={styles.actionButtons}>
                    <Button
                      type="primary"
                      icon={<DownloadOutlined />}
                      size="large"
                      onClick={handleDownload}
                    >
                      下载压缩图片
                    </Button>
                    
                    <Button
                      onClick={() => {
                        setOriginalImage(null);
                        setCompressedImage(null);
                      }}
                    >
                      重新上传
                    </Button>
                  </div>
                </div>
              )}
            </div>
          </Card>
          
          <div className={styles.toolTips}>
            <h3>使用提示</h3>
            <ul>
              <li>压缩后的图片质量与原图相比可能会有所降低，请根据您的需求选择合适的压缩质量</li>
              <li>对于网页使用的图片，建议质量设置为70-80之间，可以获得较好的体积与质量平衡</li>
              <li>对于需要保存细节的照片，建议质量设置为80-90之间</li>
              <li>处理后的图片会保持原始图片的尺寸大小</li>
            </ul>
          </div>
        </div>
      </div>
    </Layout>
  );
};

export default ImageCompressPage; 